﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using DGSFramework;
using System.Xml.Linq;
using System.Web.UI.HtmlControls;

namespace Framework
{
    public partial class ProductDetails : System.Web.UI.Page
    {
        public DGSFrameworkEntities entity = new DGSFrameworkEntities();

        public List<udv_Categories> allCate = new List<udv_Categories>();
        public List<udv_Articles> allArt = new List<udv_Articles>();
        public List<udv_Products> allPro = new List<udv_Products>();

        public udv_Products productDetails = new udv_Products();
        public List<udv_Products> lstProductRelate = new List<udv_Products>();

        protected void Page_Load(object sender, EventArgs e)
        {
            Form.DefaultButton = btnSearch.UniqueID;

            if (!IsPostBack)
            {
                txtSearch.Attributes["placeholder"] = Globals.GetLanguage("Nhập tìm kiếm ở đây", "Enter search here", true);
                LoadCacheCategory();
                LoadCacheArticle();
                LoadCacheProduct();

                LoadProductDetails();
            }
        }

        public void LoadCacheCategory()
        {
            if (Cache["Category"] == null)
            {
                Cache["Category"] = allCate = entity.udv_Categories.ToList();
            }
            else
            {
                allCate = (List<udv_Categories>)Cache["Category"];
            }
        }

        public void LoadCacheArticle()
        {
            if (Cache["Article"] == null)
            {
                Cache["Article"] = allArt = entity.udv_Articles.Include("udv_Categories").ToList();
            }
            else
            {
                allArt = (List<udv_Articles>)Cache["Article"];
            }
        }

        public void LoadCacheProduct()
        {
            if (Cache["Product"] == null)
            {
                Cache["Product"] = allPro = entity.udv_Products.Include("udv_Categories").Include("udv_ProductComments").ToList();
            }
            else
            {
                allPro = (List<udv_Products>)Cache["Product"];
            }
        }

        public string GetDefaultTitlePage()
        {
            XDocument xDocInfo = XDocument.Load(Server.MapPath(ConfigPaths.Path_Infomation_Xml));

            XElement xEInfomationConfigWebsite = xDocInfo.Descendants("ConfigWebsite").FirstOrDefault();
            return xEInfomationConfigWebsite.Element("Title").Value.Trim();
        }

        public string GetDefaultMetaDescription()
        {
            XDocument xDocInfo = XDocument.Load(Server.MapPath(ConfigPaths.Path_Infomation_Xml));

            XElement xEInfomationConfigWebsite = xDocInfo.Descendants("ConfigWebsite").FirstOrDefault();
            return xEInfomationConfigWebsite.Element("MetaDescription").Value.Trim();
        }

        public string GetDefaultMetaKeyword()
        {
            XDocument xDocInfo = XDocument.Load(Server.MapPath(ConfigPaths.Path_Infomation_Xml));

            XElement xEInfomationConfigWebsite = xDocInfo.Descendants("ConfigWebsite").FirstOrDefault();
            return xEInfomationConfigWebsite.Element("MetaKeywords").Value.Trim();
        }

        public string GetDefaultMetaTitle()
        {
            XDocument xDocInfo = XDocument.Load(Server.MapPath(ConfigPaths.Path_Infomation_Xml));

            XElement xEInfomationConfigWebsite = xDocInfo.Descendants("ConfigWebsite").FirstOrDefault();
            return xEInfomationConfigWebsite.Element("MetaTitle").Value.Trim();
        }

        public void AddTag(string metaDescription, string metaKeywords, string metaTitle, string pageTitle)
        {
            if (string.IsNullOrEmpty(metaDescription))
            {
                metaDescription = GetDefaultMetaDescription();
            }
            if (string.IsNullOrEmpty(metaKeywords))
            {
                metaKeywords = GetDefaultMetaKeyword();
            }
            if (string.IsNullOrEmpty(pageTitle))
            {
                pageTitle = GetDefaultTitlePage();
            }
            if (string.IsNullOrEmpty(metaTitle))
            {
                metaTitle = GetDefaultMetaTitle();
            }
            HtmlHead headTag = (HtmlHead)this.Master.FindControl("Head1");
            headTag.Title = pageTitle;
            HtmlMeta PagemetaTag = new HtmlMeta();
            PagemetaTag.Name = "description";
            PagemetaTag.Content = metaDescription;
            headTag.Controls.AddAt(2, PagemetaTag);
            PagemetaTag = new HtmlMeta();
            PagemetaTag.Name = "keywords";
            PagemetaTag.Content = metaKeywords;
            headTag.Controls.AddAt(3, PagemetaTag);
            PagemetaTag = new HtmlMeta();
            PagemetaTag.Name = "title";
            PagemetaTag.Content = metaTitle;
            headTag.Controls.AddAt(4, PagemetaTag);
        }

        public void LoadProductDetails()
        {
            if (Request.QueryString["ProductID"] != null)
            {
                int productID;
                int.TryParse(Request.QueryString["ProductID"].ToString(), out productID);
                productDetails = entity.udv_Products.Where(ar => ar.ProductID == productID).FirstOrDefault();
                if (productDetails == null)
                {
                    Response.Redirect(ResolveUrl("~/" + Globals.GetUrl("Errors", "Errors.aspx")));
                }
                else
                {
                    string strUrlOriginal = ConfigPaths.Domain_Url + Globals.GetUrl(productDetails.UrlRewrite, Globals.GetUrlAspx(productDetails.UrlRewrite, false) + productDetails.ProductID);
                    if (CheckUrlOriginal(strUrlOriginal) == false)
                    {
                        Response.Redirect(strUrlOriginal);
                    }

                    productDetails.TotalViews += 1;
                    entity.SaveChanges();

                    //load images product
                    var imageByProduct = entity.udv_ProductImages.Where(pi => pi.udv_Products.ProductID == productDetails.ProductID).OrderByDescending(pi => pi.AddedDate).ToList();
                    imageByProduct.Add(new udv_ProductImages() { Title = productDetails.Title, Title_en = productDetails.Title_en, ImageAlt = productDetails.ImageAlt, ImageUrl = productDetails.ImageUrl });
                    imageByProduct.Reverse();
                    rpProductImage.DataSource = imageByProduct;
                    rpProductImage.DataBind();
                    if (imageByProduct.Count > 1)
                    {
                        pnProductImageThumbnail.Visible = true;
                        rpProductImageThumbnail.DataSource = imageByProduct;
                        rpProductImageThumbnail.DataBind();
                    }
                    else
                    {
                        pnProductImageThumbnail.Visible = false;
                    }
                    //Load infomation product
                    ltrProductTitle.Text = Globals.GetLanguage(productDetails.Title, productDetails.Title_en, true);
                    ltrViewCount.Text = productDetails.TotalViews.ToString();
                    ltrProductPrice.Text = decimal.Parse(productDetails.PromotionPrice.ToString()) != 0 ? (String.Format("{0:0,0}", productDetails.PromotionPrice) + " VND") : (decimal.Parse(productDetails.SalePrice.ToString()) == 0 ? Globals.GetLanguage("Liên hệ lấy giá", "Call to get price", true) : (String.Format("{0:0,0}", productDetails.SalePrice)) + " VND");
                    ltrSummary.Text = Globals.TruncateString(Globals.GetLanguage(productDetails.Summary, productDetails.Summary_en, true), 500);
                    ltrProductDescription.Text = Globals.GetLanguage(productDetails.Description, productDetails.Description_en, true);
                    ltrProductFeatured.Text = Globals.GetLanguage(productDetails.Feature, productDetails.Feature_en, true);
                    //facebook
                    if (productDetails.CommentsEnabled == true)
                        divFacebook.Attributes["data-href"] = ConfigPaths.Domain_Url + Globals.GetUrl(productDetails.UrlRewrite, Globals.GetUrlAspx(productDetails.UrlRewrite, false) + productDetails.ProductID.ToString());
                    else
                        divFacebook.Visible = false;
                    //related product
                    productDetails.udv_CategoriesReference.Load();
                    LoadCateLevel(productDetails.udv_Categories);
                    LoadBreadcrumb(productDetails.udv_Categories.CateID, ref rpBreadcrumb);
                    rpRelateTop.DataSource = GetArticleRelate("top", productDetails);
                    rpRelateTop.DataBind();
                    lstProductRelate = GetProductRelate("product", productDetails);
                    if (lstProductRelate.Count > 0)
                    {
                        //so box tren 1 trang. Qui doi so san pham tren 1 trang thanh so box tren 1 trang
                        int boxPerPage = 0;
                        //tong so box
                        int allBox = 0;
                        //So san pham tren 1 trang
                        int productPerPage = lstProductRelate.Count;
                        List<int> allBoxInPage = new List<int>();
                        if (productPerPage % 4 == 0)
                        {
                            boxPerPage = productPerPage / 4;
                        }
                        else
                        {
                            boxPerPage = productPerPage / 4 + 1;
                        }
                        allBox = (productPerPage * boxPerPage) % productPerPage > 0 ? ((productPerPage * boxPerPage) / productPerPage) + 1 : (productPerPage * boxPerPage) / productPerPage;
                        for (int i = 0; i < allBox; i++)
                        {
                            allBoxInPage.Add(i);
                        }
                        rpProduct.DataSource = allBoxInPage;
                        rpProduct.DataBind();
                    }

                    AddTag(!string.IsNullOrEmpty(productDetails.MetaDescription) ? productDetails.MetaDescription : Globals.TruncateString(productDetails.Summary, 1000),
                        productDetails.MetaKeywords,
                        !string.IsNullOrEmpty(productDetails.MetaTitle) ? productDetails.MetaTitle : productDetails.Title,
                        !string.IsNullOrEmpty(productDetails.MetaTitle) ? productDetails.MetaTitle : productDetails.Title);

                    if (!string.IsNullOrEmpty(productDetails.MetaOrther))
                    {
                        ltrMetaOrther.Text = productDetails.MetaOrther;
                    }
                }
            }
            else
            {
                Response.Redirect(ResolveUrl("~/" + Globals.GetUrl("Errors", "Errors.aspx")));
            }
        }

        public void LoadCateLevel(udv_Categories cateCurrent)
        {
            List<udv_Categories> lstCateLevel = allCate
                .Where(ca => ca.IsActive == true && ca.ParentID == cateCurrent.CateID).ToList();
            ltrParentCate.Text = Globals.GetLanguage(cateCurrent.Title, cateCurrent.Title_en, true);
            if (lstCateLevel.Count == 0)
            {
                lstCateLevel = allCate
                .Where(ca => ca.IsActive == true && ca.ParentID == cateCurrent.ParentID).ToList();
                udv_Categories cateParent = allCate.Where(ca=>ca.CateID == cateCurrent.ParentID).FirstOrDefault();
                if (cateParent.CateID != ConfigPaths.Category_Article_ID && cateParent.CateID != ConfigPaths.Category_Product_ID)
                {
                    ltrParentCate.Text = Globals.GetLanguage(cateParent.Title, cateParent.Title_en, true);
                }
            }
            rpCateLevel.DataSource = lstCateLevel;
            rpCateLevel.DataBind();
        }

        public void LoadBreadcrumb(int cateID, ref Repeater rpBreadcrumb)
        {
            List<udv_Categories> allCateChild = new List<udv_Categories>();
            LoopCategoryChild(ref allCateChild, cateID);
            allCateChild.RemoveAt(0);

            rpBreadcrumb.DataSource = allCateChild;
            rpBreadcrumb.DataBind();
        }

        public void LoopCategoryChild(ref List<udv_Categories> allCateChild, int cateID)
        {
            udv_Categories cate = allCate.Where(ca => ca.CateID == cateID).FirstOrDefault();
            if (cate != null)
            {
                allCateChild.Insert(0, cate);
                LoopCategoryChild(ref allCateChild, cate.ParentID.Value);
            }
        }

        public List<udv_Articles> GetArticleRelate(string position, udv_Products product)
        {
            List<udv_Articles> lstArticleRelate = new List<udv_Articles>();
            product.udv_Relate.Load();
            var lstRelate = product.udv_Relate.Where(tg => tg.Position.ToLower().Trim() == position.ToLower().Trim()).ToList();
            lstRelate.ForEach(tg => lstArticleRelate.Add(allArt.Where(ar => ar.ArticleID == tg.PostID).FirstOrDefault()));
            return lstArticleRelate;
        }

        public List<udv_Products> GetProductRelate(string position, udv_Products product)
        {
            List<udv_Products> lstGetProductRelate = new List<udv_Products>();
            product.udv_Relate.Load();
            var lstRelate = product.udv_Relate.Where(tg => tg.Position.ToLower().Trim() == position.ToLower().Trim()).ToList();
            lstRelate.ForEach(tg => lstGetProductRelate.Add(allPro.Where(ar => ar.ProductID == tg.PostID).FirstOrDefault()));
            return lstGetProductRelate;
        }

        public bool CheckUrlOriginal(string urlOriginal)
        {
            string strUrlRequest = ConfigPaths.Domain_Url.Substring(0, ConfigPaths.Domain_Url.Length - 1) + (Request.ServerVariables["HTTP_X_REWRITE_URL"] != null ? Request.ServerVariables["HTTP_X_REWRITE_URL"].ToString() : Request.RawUrl);
            if (strUrlRequest.ToLower().Trim() == urlOriginal.ToLower().Trim())
            {
                return true;
            }
            else
            {
                return false;
            }
        }

        protected void rpProduct_ItemDataBound(object sender, RepeaterItemEventArgs e)
        {
            int page = 1;
            Repeater rpGameByCateSub = (Repeater)e.Item.FindControl("rpProductSub");
            var lstGameByCateFirst = lstProductRelate
                .Where(ar => ar.IsActive == true && ((ar.ReleaseDate != null && ar.ExpireDate != null) ? (ar.ReleaseDate <= DateTime.Now && ar.ExpireDate >= DateTime.Now) : ((ar.ReleaseDate <= DateTime.Now || ar.ExpireDate >= DateTime.Now) || (ar.ReleaseDate == null && ar.ExpireDate == null))))
                .OrderBy(pr => pr.DisplayOrder)
                .ThenByDescending(pr => pr.AddedDate)
                .Skip(e.Item.ItemIndex * 4 + lstProductRelate.Count * (page - 1))
                .Take(4 * (e.Item.ItemIndex + 1) <= lstProductRelate.Count ? 4 : lstProductRelate.Count - (4 * e.Item.ItemIndex)).ToList();
            rpGameByCateSub.DataSource = lstGameByCateFirst;
            rpGameByCateSub.DataBind();
        }

        protected void btnSearch_Click(object sender, EventArgs e)
        {
            string textSearch = txtSearch.Text.Trim();
            Response.Redirect(ResolveUrl("~/" + DGSFramework.Globals.GetUrl("tim-kiem-san-pham/" + Server.UrlEncode(textSearch), "SearchProduct.aspx?Keyword=" + Server.UrlEncode(textSearch))));
        }
    }
}